package com.tarena.lbs.user.dao.repository.impl;

import com.alibaba.cloud.commons.lang.StringUtils;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.tarena.lbs.base.common.utils.Asserts;
import com.tarena.lbs.base.protocol.exception.BusinessException;
import com.tarena.lbs.user.dao.mapper.AdminMapper;
import com.tarena.lbs.user.dao.repository.AdminRepository;
import com.tarena.lbs.user.pojo.po.AdminPO;
import com.tarena.lbs.user.pojo.query.AdminQuery;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import java.util.Date;
import java.util.List;
@Slf4j
@Repository
public class AdminRepositoryImpl implements AdminRepository {

    @Autowired
    private AdminMapper adminMapper;

    @Override
    public AdminPO getAdminByPhone(String phone) {
        QueryWrapper<AdminPO> query = new QueryWrapper<>();
        query.eq("account_phone",phone);
        query.eq("deleted", 0); // 默认不查询已删除的记录
        return adminMapper.selectOne(query);
    }

    @Override
    public AdminPO getAdminById(Integer id) {
        QueryWrapper<AdminPO> query = new QueryWrapper<>();
        query.eq("id", id);
        query.eq("deleted", 0); // 默认不查询已删除的记录
        return adminMapper.selectOne(query);
    }

    @Override
    public PageInfo<AdminPO> pagesList(AdminQuery query) {
        QueryWrapper<AdminPO> queryWrapper = assembleAdminQuery(query);
        //PageHelper.startPage 之间不能有代码
        PageHelper.startPage(query.getPageNo(), query.getPageSize());
        List<AdminPO> pos = adminMapper.selectList(queryWrapper);
        //selectList 数据库操作 之间不能有代码
        return new PageInfo<>(pos);
    }


    @Override
    public void save(AdminPO adminPO) {
        adminMapper.insert(adminPO);
    }

    @Override
    public void update(AdminPO adminPO) throws BusinessException {
        // 确保ID不为空
        Asserts.isTrue(adminPO.getId() == null || adminPO.getId() <= 0,
                new BusinessException("-1", "更新ID不能为空"));

        // 确保更新时间不为空
        if (adminPO.getUpdateTime() == null) {
            adminPO.setUpdateTime(new Date());
        }

        // 使用MyBatis-Plus的updateById方法更新数据
        int result = adminMapper.updateById(adminPO);
        if (result != 1) {
            throw new BusinessException("-1", "更新账号失败");
        }
    }

    @Override
    public void delete(Integer id) throws BusinessException {
        // 假删除：更新deleted字段为1（表示已删除）
        AdminPO adminPO = new AdminPO();
        adminPO.setId(id);
        adminPO.setDeleted(1);
        int result = adminMapper.updateById(adminPO);
        if (result != 1) {
            throw new BusinessException("-1", "删除账号失败");
        }
    }


    @Override
    public int deleteAdmin(Integer id) {
        // 假删除：更新deleted字段为1（表示已删除）
        AdminPO adminPO = new AdminPO();
        adminPO.setId(id);
        adminPO.setDeleted(1);
        return adminMapper.updateById(adminPO);
    }



    @Override
    public void updateStatus(Integer id, Integer status) throws BusinessException {

    }


    @Override
    public void assignRole(Integer id, Integer accountType, Integer businessId) throws BusinessException {
        // 创建更新对象
        AdminPO adminPO = new AdminPO();
        adminPO.setId(id);
        adminPO.setAccountType(accountType);
        adminPO.setUpdateTime(new Date()); // 添加更新时间
    
        // 如果是商家管理员，需要设置传入的businessId
        if (accountType == 1) {
            // 确保传入的businessId不为空
            if (businessId == null) {
                throw new BusinessException("-1", "商家管理员必须关联商家ID");
            }
            // 设置businessId到更新对象中
            adminPO.setBusinessId(businessId);
        } else {
            // 平台管理员不需要关联商家ID，清空businessId
            adminPO.setBusinessId(null);
        }
    
        // 调用Mapper层更新角色
        int result = adminMapper.updateById(adminPO);
        if (result != 1) {
            throw new BusinessException("-1", "角色分配失败");
        }
    }

    @Override
    public void resetPassword(Integer id) throws BusinessException {
        // 校验管理员是否存在
        AdminPO adminPO = getAdminById(id);
        if (adminPO == null) {
            throw new BusinessException("-1", "管理员不存在或已被删除");
        }

        // 生成默认密码（示例使用"123456"，实际应用中应该加密存储）
        String defaultPassword = "123456";

        // 更新密码
        AdminPO updatePO = new AdminPO();
        updatePO.setId(id);
        updatePO.setAccountPassword(defaultPassword); // 实际应用中应该加密
        updatePO.setUpdateTime(new Date());
        // 调用Mapper层更新密码
        int result = adminMapper.updateById(updatePO);
        if (result != 1) {
            throw new BusinessException("-1", "密码重置失败");
        }
    }



    @Override
    public void batchDelete(List<Integer> ids) throws BusinessException {
        if (ids == null || ids.isEmpty()) {
            throw new BusinessException("-1", "删除列表不能为空");
        }
        for (Integer id : ids) {
            delete(id); // 复用单条删除逻辑，执行假删除
        }
    }


    // 新增批量更新状态的方法
    public void batchUpdateStatus(List<Integer> ids, Integer status) {
        adminMapper.updateStatusBatch(ids, status);
    }

    // 新增根据角色类型查询的方法
    public List<AdminPO> getAdminsByType(Integer accountType) {
        return adminMapper.selectByAccountType(accountType);
    }

    // 新增根据商家ID查询的方法
    public List<AdminPO> getAdminsByBusinessId(Integer businessId) {
        return adminMapper.selectByBusinessId(businessId);
    }

    // 辅助方法：组装查询条件
    private QueryWrapper<AdminPO> assembleAdminQuery(AdminQuery query) {
        QueryWrapper<AdminPO> queryWrapper = new QueryWrapper<>();

        // 默认查询未删除的记录
        queryWrapper.eq("deleted", 0);

        if (query != null) {
            if (StringUtils.isNotEmpty(query.getAccountPhone())) {
                queryWrapper.like("account_phone", query.getAccountPhone());
            }
            if (StringUtils.isNotEmpty(query.getNickname())) {
                queryWrapper.like("nickname", query.getNickname());
            }
            if (query.getBusinessId() != null) {
                queryWrapper.eq("business_id", query.getBusinessId());
            }
        }


        //1.accountPhone 账号手机号 相等查询 where account_phone=#{phone}
        if (StringUtils.isNotBlank(query.getAccountPhone())){
            queryWrapper.eq("account_phone",query.getAccountPhone());
        }
        //2.nickname 昵称 模糊查询 非空 where nickname like(%#{}%)
        if (StringUtils.isNotBlank(query.getNickname())){
            queryWrapper.like("nickname",query.getNickname());
        }
        //3.businessId 商家ID 相等查询
        if (query.getBusinessId() != null){
            queryWrapper.eq("business_id", query.getBusinessId());
        }
        // 添加排序
        queryWrapper.orderByDesc("create_time");
        return queryWrapper;
    }

}